//
//  CosWebSorcket.swift
//  CosClub_Basis
//
//  Created by iOS on 2020/5/18.
//  Copyright © 2020 iOS. All rights reserved.
//

import Foundation
import Starscream


let webSocket = WebSocketSingle.shared

final class WebSocketSingle: NSObject, WebSocketDelegate {
    var isConnected = false
    func didReceive(event: WebSocketEvent, client: WebSocket) {
        switch event {
        case .connected(let headers):
            isConnected = true
            print("websocket is connected: \(headers)")
        case .disconnected(let reason, let code):
            isConnected = false
            print("websocket is disconnected: \(reason) with code: \(code)")
        case .text(let string):
            print("Received text: \(string)")
        case .binary(let data):
            print("Received data: \(data.count)")
        case .ping(_):
            break
        case .pong(_):
            break
        case .viabilityChanged(_):
            break
        case .reconnectSuggested(_):
            break
        case .cancelled:
            isConnected = false
            Log("socket取消")
        case .error(let error):
            isConnected = false
//            handleError(error)
            Log("socket连接上error失败")
        }
    }

    
    //构造单例数据
    static let shared = WebSocketSingle()
    private override init() {
    }
}

// initSocket方法
public func initWebSocketSingle () {
    SingletonSocket.sharedInstance.socket.delegate = webSocket
    if !webSocket.isConnected {
        SingletonSocket.sharedInstance.socket.connect()
    }
}

//声明webSocket单例
open class SingletonSocket {
    //socketURL为websocket地址
    let socket:WebSocket = WebSocket(request: URLRequest(url: URL(string: "ws://10.1.1.14:30000/v1.0/theatre?theatreId=123456789&userId=123")!))
    
//    let socket:WebSocket = WebSocket(request: URLRequest(url: URL(string: "ws://192.168.13.184:8080/v1.0/theatre?theatreId=123456789&userId=123")!))
    
    public class var sharedInstance : SingletonSocket{
        struct Static{
            static let instance:SingletonSocket = SingletonSocket()
        }
        return Static.instance
    }
    
    public func sendMsg(text: String) {
        socket.write(string: text)
    }
}






